/**
 * Created by chench on 2016/8/23.
 */

//全局变量
var board=new Array();
var hasConflicted = new Array();
var score = 0;


$(function () {
    newgame();
});

function newgame() {
    //初始化棋盘格
    init();
    //生成数字格
    generateOneNumber();
    generateOneNumber();

}

function init() {
    //遍历
    for(var i=0;i<4;i++)
    {
        board[i]=new Array();
        hasConflicted[i]=new Array();
        for(var j=0;j<4;j++)
        {
            board[i][j]=0;
            hasConflicted[i][j]=false;
            var gridcell=$("#grid-cell-"+i+"-"+j);
            //to top
            gridcell.css("top",getPosTop(i,j));
            //to left
            gridcell.css("left",getPosLeft(i,j));
        }
    }
    updateBoardView();
}

function updateBoardView() {
    $(".number-cell").remove();
    for(var i=0;i<4;i++)
    {
        for(var j=0;j<4;j++)
        {
            $("#grid-container").append("<div class='number-cell' id='number-cell-"+i+"-"+j+"'></div>");
            var numberCell = $("#number-cell-"+i+"-"+j);
            //css样式
            if (board[i][j] == 0)
            {
                numberCell.css("width", "0px");
                numberCell.css("height", "0px");
                numberCell.css("top", getPosTop(i, j) + 50);
                numberCell.css("left", getPosLeft(i, j) + 50);
            }
            else
            {
                numberCell.css("width", "100px");
                numberCell.css("height", "100px");
                numberCell.css("top", getPosTop(i, j));
                numberCell.css("left", getPosLeft(i, j));
                numberCell.css("background-color", getNumberBackgroundColor(board[i][j]));
                numberCell.css("color", getNumberColor(board[i][j]));
                numberCell.text(board[i][j]);
            }
            hasConflicted[i][j] = false;
        }
    }
    $(".number-cell").css("line-height", "100px");
    $(".number-cell").css("font-size", "60px");
}

function generateOneNumber() {
    if (nospace(board)) {
        return false;
    }
    //随机位置
    var randx=parseInt(Math.floor(Math.random()*4));
    var randy=parseInt(Math.floor(Math.random()*4));
    while(true)
    {
        if(board[randx][randy]==0)
        {
            break;
        }
        var randx=parseInt(Math.floor(Math.random()*4));
        var randy=parseInt(Math.floor(Math.random()*4));
    }
    //2或4
    var randNumber=Math.random()<0.5?2:4;
    board[randx][randy]=randNumber;

    //显示动画
    ShowNumberWithAnimation(randx,randy,randNumber);
}
function restartgame() {
    $("#gameover").remove();
    updateScore(0);
    newgame();
}
